import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:meal/constant/antd_icons.dart';
import 'package:meal/constant/fonts.dart';
import 'package:meal/constant/sizes.dart';
import 'package:meal/event/event_model.dart';
import 'package:meal/route/route.dart';
import 'package:meal/ui/draw_under_line.dart';
import 'package:meal/utils/colors.dart';
import 'package:meal/utils/styles.dart';
import 'package:meal/utils/tools.dart';

class IndexPage extends StatefulWidget {
  const IndexPage({Key? key}) : super(key: key);

  @override
  State<IndexPage> createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage>
    with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  bool show = false;

  late AnimationController controller;

  late Animation<double> animation;

  List<String> bizStatus = ['营业中', '待营业', '休息中'];

  final GlobalKey _bizStatusKey = GlobalKey();

  OverlayEntry? _overlayEntry;

  final GlobalKey actionKey = GlobalKey();

  @override
  void initState() {
    super.initState();
    controller = AnimationController(
        duration: const Duration(milliseconds: 300), vsync: this);
    animation = CurvedAnimation(parent: controller, curve: Curves.linear);
    controller.reverse();
    globalBus
        .on<ClosedOverlayEntryEvent>()
        .listen((ClosedOverlayEntryEvent event) {
      dismissOverlay();
    });
  }

  @override
  void dispose() {
    super.dispose();
    _overlayEntry?.remove();
    _overlayEntry = null;
    controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      backgroundColor: ColorsUtils.rgba(245, 245, 245),
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: Text('首页',
            style: StylesUtils.customTextStyle(fontSize: Sizes.default18)),
        centerTitle: true,
        backgroundColor: ColorsUtils.rgba(255, 110, 83, 1),
        elevation: 0,
        actions: [
          IconButton(
              icon: ImageIcon(ToolsUtils.assetImageIcon('msg.png')),
              iconSize: Sizes.default20,
              onPressed: () {
                Get.toNamed(RouteGet.messageType);
              }),
        ],
        systemOverlayStyle: SystemUiOverlayStyle.light,
        bottom: PreferredSize(
            preferredSize: const Size.fromHeight(Sizes.default115),
            child: Stack(
              key: _bizStatusKey,
              clipBehavior: Clip.none,
              children: [
                Container(
                  padding:
                      const EdgeInsets.symmetric(vertical: Sizes.default10),
                  child: Row(
                    children: [
                      Container(
                        padding: const EdgeInsets.only(left: Sizes.default20),
                        alignment: Alignment.center,
                        child: ClipOval(
                            child: ToolsUtils.getAssetImage('shop_header.png',
                                width: Sizes.default60,
                                height: Sizes.default60)),
                      ),
                      Container(
                        width: Sizes.default180,
                        padding: const EdgeInsets.only(top: Sizes.default10),
                        margin: const EdgeInsets.only(left: Sizes.default20),
                        child: Column(
                          children: [
                            Container(
                              alignment: Alignment.centerLeft,
                              child: Text('默林如斯的广东肠粉早餐店(凤凰广场店)',
                                  style: StylesUtils.customTextStyle(
                                      fontWeight: Fonts.w5,
                                      fontSize: Sizes.default15)),
                            ),
                            Container(
                              alignment: Alignment.centerLeft,
                              margin:
                                  const EdgeInsets.only(top: Sizes.default10),
                              child: Text(
                                '查看店铺详情',
                                style: StylesUtils.customTextStyle(
                                    fontSize: Sizes.default13,
                                    color: ColorsUtils.colorFffFb2),
                              ),
                            )
                          ],
                        ),
                      )
                    ],
                  ),
                ),
                Positioned(
                  right: 0,
                  bottom: 20,
                  key: actionKey,
                  child: InkWell(
                    onTap: () {
                      // showPopWindow(context);
                      openOverlay(context);
                    },
                    child: Container(
                      height: Sizes.default30,
                      width: Sizes.default80,
                      padding: const EdgeInsets.only(left: Sizes.default15),
                      alignment: Alignment.centerLeft,
                      decoration: BoxDecoration(
                          color: ColorsUtils.rgba(
                              255, 255, 255, 0.298039215686275),
                          borderRadius: const BorderRadius.only(
                              topLeft: Radius.circular(Sizes.default15),
                              bottomLeft: Radius.circular(Sizes.default15))),
                      child: Text.rich(
                          TextSpan(children: [
                            TextSpan(
                              text: '营业中',
                              style: StylesUtils.defaultTextStyle(),
                            ),
                            WidgetSpan(
                                child: ImageIcon(
                              ToolsUtils.assetImageIcon(
                                  'arrow-right-filling.png'),
                              size: Sizes.default15,
                              color: Colors.white,
                            ))
                          ]),
                          textDirection: TextDirection.ltr),
                    ),
                  ),
                ),
                // positionBiz()
              ],
            )),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              height: 130,
              decoration: const BoxDecoration(color: Colors.white),
              child: GridView(
                padding: const EdgeInsets.symmetric(
                    vertical: Sizes.default15, horizontal: Sizes.default10),
                physics: const NeverScrollableScrollPhysics(),
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 4,
                    crossAxisSpacing: 10,
                    childAspectRatio: 0.76),
                children: [
                  InkWell(
                    onTap: () {
                      Get.toNamed(RouteGet.productManage);
                    },
                    child: Column(
                      children: [
                        Center(
                          child: ToolsUtils.getAssetImageIcon('commodity.png',
                              width: 70, height: 70),
                        ),
                        Container(
                          margin: const EdgeInsets.only(top: Sizes.default5),
                          alignment: Alignment.center,
                          child: Text(
                            '商品管理',
                            style: StylesUtils.customTextStyle(
                                fontSize: Sizes.default15,
                                color: ColorsUtils.color363),
                          ),
                        )
                      ],
                    ),
                  ),
                  InkWell(
                    onTap: () {
                      Get.toNamed(RouteGet.financeManage);
                    },
                    child: Column(
                      children: [
                        Center(
                          child: ToolsUtils.getAssetImageIcon('finance.png',
                              width: 70, height: 70),
                        ),
                        Container(
                          margin: const EdgeInsets.only(top: Sizes.default5),
                          alignment: Alignment.center,
                          child: Text(
                            '财务管理',
                            style: StylesUtils.customTextStyle(
                                fontSize: Sizes.default15,
                                color: ColorsUtils.color363),
                          ),
                        )
                      ],
                    ),
                  ),
                  InkWell(
                    onTap: () {
                      Get.toNamed(RouteGet.evaluateManage);
                    },
                    child: Column(
                      children: [
                        Center(
                          child: ToolsUtils.getAssetImageIcon('evaluation.png',
                              width: 70, height: 70),
                        ),
                        Container(
                          margin: const EdgeInsets.only(top: Sizes.default5),
                          alignment: Alignment.center,
                          child: Text(
                            '评价管理',
                            style: StylesUtils.customTextStyle(
                                fontSize: Sizes.default15,
                                color: ColorsUtils.color363),
                          ),
                        )
                      ],
                    ),
                  ),
                  InkWell(
                    onTap: () {
                      Get.toNamed(RouteGet.groupManage);
                    },
                    child: Column(
                      children: [
                        Center(
                          child: ToolsUtils.getAssetImageIcon('purchase.png',
                              width: 70, height: 70),
                        ),
                        Container(
                          margin: const EdgeInsets.only(top: Sizes.default5),
                          alignment: Alignment.center,
                          child: Text(
                            '团购优惠',
                            style: StylesUtils.customTextStyle(
                                fontSize: Sizes.default15,
                                color: ColorsUtils.color363),
                          ),
                        )
                      ],
                    ),
                  )
                ],
              ),
            ),
            Container(
              margin: const EdgeInsets.only(top: Sizes.default10),
              decoration: const BoxDecoration(
                color: Colors.white,
              ),
              child: Column(
                children: [
                  SizedBox(
                    height: Sizes.default50,
                    child: DrawUnderLine(
                      child: Container(
                        padding: const EdgeInsets.symmetric(
                            horizontal: Sizes.default15),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text('经营数据',
                                style: StylesUtils.customTextStyle(
                                    fontSize: Sizes.default13,
                                    fontWeight: Fonts.w7,
                                    color: ColorsUtils.color333)),
                            InkWell(
                              onTap: () {
                                Get.toNamed(RouteGet.tradeStatistics);
                              },
                              child: Text.rich(TextSpan(
                                  text: '更多',
                                  style: StylesUtils.customTextStyle(
                                      fontSize: Sizes.default13,
                                      color: ColorsUtils.color797),
                                  children: [
                                    WidgetSpan(
                                        child: Icon(
                                          AntdIcons.right,
                                          size: Sizes.default14,
                                          color: ColorsUtils.colorFromHexString(
                                              ColorsUtils.color797),
                                        ),
                                        alignment: PlaceholderAlignment.middle)
                                  ])),
                            )
                          ],
                        ),
                      ),
                    ),
                  ),
                  Container(
                    padding: const EdgeInsets.only(
                        top: Sizes.default15, bottom: Sizes.default20),
                    child: Row(
                      children: [
                        Expanded(
                            child: Column(
                          children: [
                            Center(
                              child: Text('今日订单',
                                  style: StylesUtils.customTextStyle(
                                      fontSize: Sizes.default15,
                                      color: ColorsUtils.color333)),
                            ),
                            Container(
                              margin: const EdgeInsets.only(
                                  top: Sizes.default10,
                                  bottom: Sizes.default20),
                              alignment: Alignment.center,
                              child: Text(
                                '1000',
                                style: StylesUtils.customTextStyle(
                                    color: ColorsUtils.colorCc0,
                                    fontSize: Sizes.default18),
                              ),
                            ),
                            Center(
                              child: Text('昨日',
                                  style: StylesUtils.customTextStyle(
                                      fontSize: Sizes.default15,
                                      color: ColorsUtils.color333)),
                            ),
                            Container(
                              margin:
                                  const EdgeInsets.only(top: Sizes.default10),
                              alignment: Alignment.center,
                              child: Text(
                                '1057',
                                style: StylesUtils.customTextStyle(
                                    color: ColorsUtils.colorCc0,
                                    fontSize: Sizes.default18),
                              ),
                            )
                          ],
                        )),
                        Expanded(
                            child: Column(
                          children: [
                            Center(
                              child: Text('今日营业额',
                                  style: StylesUtils.customTextStyle(
                                      fontSize: Sizes.default15,
                                      color: ColorsUtils.color333)),
                            ),
                            Container(
                              margin: const EdgeInsets.only(
                                  top: Sizes.default10,
                                  bottom: Sizes.default20),
                              alignment: Alignment.center,
                              child: Text(
                                '17800.68',
                                style: StylesUtils.customTextStyle(
                                    color: ColorsUtils.colorCc0,
                                    fontSize: Sizes.default18),
                              ),
                            ),
                            Center(
                              child: Text('昨日',
                                  style: StylesUtils.customTextStyle(
                                      fontSize: Sizes.default15,
                                      color: ColorsUtils.color333)),
                            ),
                            Container(
                              margin:
                                  const EdgeInsets.only(top: Sizes.default10),
                              alignment: Alignment.center,
                              child: Text(
                                '91057.25',
                                style: StylesUtils.customTextStyle(
                                    color: ColorsUtils.colorCc0,
                                    fontSize: Sizes.default18),
                              ),
                            )
                          ],
                        )),
                        Expanded(
                            child: Column(
                          children: [
                            Center(
                              child: Text('今日客单',
                                  style: StylesUtils.customTextStyle(
                                      fontSize: Sizes.default15,
                                      color: ColorsUtils.color333)),
                            ),
                            Container(
                              margin: const EdgeInsets.only(
                                  top: Sizes.default10,
                                  bottom: Sizes.default20),
                              alignment: Alignment.center,
                              child: Text(
                                '87.45',
                                style: StylesUtils.customTextStyle(
                                    color: ColorsUtils.colorCc0,
                                    fontSize: Sizes.default18),
                              ),
                            ),
                            Center(
                              child: Text('昨日',
                                  style: StylesUtils.customTextStyle(
                                      fontSize: Sizes.default15,
                                      color: ColorsUtils.color333)),
                            ),
                            Container(
                              margin:
                                  const EdgeInsets.only(top: Sizes.default10),
                              alignment: Alignment.center,
                              child: Text(
                                '57.02',
                                style: StylesUtils.customTextStyle(
                                    color: ColorsUtils.colorCc0,
                                    fontSize: Sizes.default18),
                              ),
                            )
                          ],
                        )),
                      ],
                    ),
                  )
                ],
              ),
            ),
            Container(
              margin: const EdgeInsets.only(top: Sizes.default10),
              decoration: const BoxDecoration(
                color: Colors.white,
              ),
              child: Column(
                children: [
                  Container(
                    height: Sizes.default40,
                    padding:
                        const EdgeInsets.symmetric(horizontal: Sizes.default15),
                    alignment: Alignment.centerLeft,
                    child: Text('经营活动',
                        style: StylesUtils.customTextStyle(
                            fontSize: Sizes.default13,
                            fontWeight: Fonts.w7,
                            color: ColorsUtils.color333)),
                  ),
                  Container(
                    padding:
                        const EdgeInsets.symmetric(vertical: Sizes.default20),
                    child: Row(
                      children: [
                        Expanded(
                            child: InkWell(
                          onTap: () {
                            Get.toNamed(RouteGet.marketCanActivity);
                          },
                          child: Column(
                            children: [
                              Center(
                                child: Text('可报名',
                                    style: StylesUtils.customTextStyle(
                                        color: ColorsUtils.color333,
                                        fontSize: Sizes.default15)),
                              ),
                              Container(
                                margin:
                                    const EdgeInsets.only(top: Sizes.default10),
                                alignment: Alignment.center,
                                child: Text('20',
                                    style: StylesUtils.customTextStyle(
                                        color: ColorsUtils.color333,
                                        fontSize: Sizes.default15)),
                              )
                            ],
                          ),
                        )),
                        Expanded(
                            child: InkWell(
                          onTap: () {
                            Get.toNamed(RouteGet.marketJoinActivity);
                          },
                          child: Column(
                            children: [
                              Center(
                                child: Text('已报名',
                                    style: StylesUtils.customTextStyle(
                                        color: ColorsUtils.color333,
                                        fontSize: Sizes.default15)),
                              ),
                              Container(
                                margin:
                                    const EdgeInsets.only(top: Sizes.default10),
                                alignment: Alignment.center,
                                child: Text('20',
                                    style: StylesUtils.customTextStyle(
                                        color: ColorsUtils.color333,
                                        fontSize: Sizes.default15)),
                              )
                            ],
                          ),
                        )),
                        Expanded(
                            child: InkWell(
                          onTap: () {
                            Get.toNamed(RouteGet.marketBuildActivity);
                          },
                          child: Column(
                            children: [
                              Center(
                                  child: Stack(
                                clipBehavior: Clip.none,
                                children: [
                                  Text('自建',
                                      style: StylesUtils.customTextStyle(
                                          color: ColorsUtils.color333,
                                          fontSize: Sizes.default15)),
                                  Positioned(
                                      right: -25,
                                      top: -10,
                                      child: Container(
                                        width: 27,
                                        height: 18,
                                        alignment: Alignment.topCenter,
                                        decoration: BoxDecoration(
                                            image: DecorationImage(
                                                alignment: Alignment.topLeft,
                                                image:
                                                    ToolsUtils.assetImageIcon(
                                                        'new.png'))),
                                        child: Text(
                                          'new',
                                          style: StylesUtils.customTextStyle(
                                              fontSize: Sizes.default10,
                                              color: ColorsUtils.colorFf6),
                                        ),
                                      ))
                                ],
                              )),
                              Container(
                                margin:
                                    const EdgeInsets.only(top: Sizes.default10),
                                alignment: Alignment.center,
                                child: Text('20',
                                    style: StylesUtils.customTextStyle(
                                        color: ColorsUtils.color333,
                                        fontSize: Sizes.default15)),
                              )
                            ],
                          ),
                        ))
                      ],
                    ),
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  void showPopWindow(BuildContext context) {
    BrnPopupListWindow.showPopListWindow(context, actionKey,
        offset: 10, data: bizStatus, onItemClick: (index, item) {
      return false;
    });
  }

  void openOverlay(BuildContext context) {
    showOverlay(context);
    setState(() {
      show = !show;
      if (show) {
        controller.forward();
      } else {
        controller.reverse();
      }
    });
  }

  Widget positionBiz() {
    return Positioned(
      right: 10,
      top: 80,
      child: ScaleTransition(
        scale: controller,
        child: Container(
          padding: const EdgeInsets.all(Sizes.default5),
          decoration: BoxDecoration(
              color: Colors.white,
              border: Border.all(color: ColorsUtils.rgba(170, 170, 170)),
              borderRadius:
                  const BorderRadius.all(Radius.circular(Sizes.default3))),
          child: Column(
            children: bizStatus
                .asMap()
                .map((key, value) => MapEntry(
                    key,
                    InkWell(
                      onTap: () {
                        setState(() {
                          show = false;
                          controller.reverse();
                        });
                      },
                      child: Container(
                        width: 54,
                        height: 24,
                        margin: EdgeInsets.only(
                            bottom: key < bizStatus.length - 1
                                ? Sizes.default5
                                : 0),
                        decoration: BoxDecoration(
                            color: ColorsUtils.colorFromHexString('#EEEEEE'),
                            border: Border.all(
                                color: ColorsUtils.rgba(170, 170, 170)),
                            borderRadius: const BorderRadius.all(
                                Radius.circular(Sizes.default3))),
                        alignment: Alignment.center,
                        child: Text(value,
                            style: StylesUtils.customTextStyle(
                                color: ColorsUtils.color333,
                                fontSize: Sizes.default12)),
                      ),
                    )))
                .values
                .toList(),
          ),
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;

  void showOverlay(BuildContext context) {
    if (_overlayEntry != null) {
      controller.reverse();
      return delayedOverlay();
    }

    ///1、获取OverlayState
    OverlayState overlayState = Overlay.of(context);

    ///2、创建OverlayEntry
    _overlayEntry = OverlayEntry(
      builder: (ctx) {
        //获取_bizStatusKey Widget的位置，用于设置OverlayEntry将悬浮的位置
        RenderBox? renderBox =
            _bizStatusKey.currentContext?.findRenderObject() as RenderBox?;
        Size size = renderBox?.size ?? Size.zero;
        Offset offset = renderBox?.localToGlobal(Offset.zero) ?? Offset.zero;
        final double top = offset.dy + size.height - 15;
        // double left = offset.dx + size.width;
        return Positioned(
          top: top,
          right: 10,
          child: Material(
            color: Colors.transparent,
            child: ScaleTransition(
              scale: controller,
              child: Column(
                children: [
                  Center(
                    child: CustomPaint(
                      size: const Size(15, 6),
                      painter: _Triangle(
                          isDownArrow: false,
                          color: Colors.white,
                          borderColor: Colors.transparent),
                    ),
                  ),
                  Container(
                    padding: const EdgeInsets.all(Sizes.default5),
                    decoration: BoxDecoration(
                        color: Colors.white,
                        border:
                            Border.all(color: ColorsUtils.rgba(170, 170, 170)),
                        borderRadius: const BorderRadius.all(
                            Radius.circular(Sizes.default3))),
                    child: Column(children: [
                      ...bizStatus
                          .asMap()
                          .map((key, value) => MapEntry(
                              key,
                              InkWell(
                                onTap: () {
                                  setState(() {
                                    dismissOverlay();
                                  });
                                },
                                child: Container(
                                  width: 54,
                                  height: 24,
                                  margin: EdgeInsets.only(
                                      bottom: key < bizStatus.length - 1
                                          ? Sizes.default5
                                          : 0),
                                  decoration: BoxDecoration(
                                      color: ColorsUtils.colorFromHexString(
                                          '#EEEEEE'),
                                      border: Border.all(
                                          color:
                                              ColorsUtils.rgba(170, 170, 170)),
                                      borderRadius: const BorderRadius.all(
                                          Radius.circular(Sizes.default3))),
                                  alignment: Alignment.center,
                                  child: Text(value,
                                      style: StylesUtils.customTextStyle(
                                          color: ColorsUtils.color333,
                                          fontSize: Sizes.default12)),
                                ),
                              )))
                          .values
                          .toList(),
                    ]),
                  )
                ],
              ),
            ),
          ),
        );
      },
    );

    ///3、将OverlayEntry插入到Overlay中。
    overlayState.insert(_overlayEntry!);
    controller.forward();
  }

  void dismissOverlay() {
    if (_overlayEntry != null) {
      controller.reverse();
      delayedOverlay();
    }
  }

  void delayedOverlay() {
    Future.delayed(const Duration(milliseconds: 100), () {
      _overlayEntry?.remove();
      _overlayEntry = null;
    });
  }
}

class _Triangle extends CustomPainter {
  bool isDownArrow;
  Color color;
  Color borderColor;

  _Triangle({
    required this.isDownArrow,
    required this.color,
    required this.borderColor,
  });

  @override
  void paint(Canvas canvas, Size size) {
    Path path = Path();
    Paint paint = Paint();
    paint.strokeWidth = 2.0;
    paint.color = color;
    paint.style = PaintingStyle.fill;

    if (isDownArrow) {
      path.moveTo(0.0, -1.5);
      path.lineTo(size.width / 2.0, size.height);
      path.lineTo(size.width, -1.5);
    } else {
      path.moveTo(0.0, size.height + 1.5);
      path.lineTo(size.width / 2.0, 0.0);
      path.lineTo(size.width, size.height + 1.5);
    }

    canvas.drawPath(path, paint);
    Paint paintBorder = Paint();
    Path pathBorder = Path();
    paintBorder.strokeWidth = 0.5;
    paintBorder.color = borderColor;
    paintBorder.style = PaintingStyle.stroke;

    if (isDownArrow) {
      pathBorder.moveTo(0.0, -0.5);
      pathBorder.lineTo(size.width / 2.0, size.height);
      pathBorder.lineTo(size.width, -0.5);
    } else {
      pathBorder.moveTo(0.5, size.height + 0.5);
      pathBorder.lineTo(size.width / 2.0, 0);
      pathBorder.lineTo(size.width - 0.5, size.height + 0.5);
    }

    canvas.drawPath(pathBorder, paintBorder);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }
}
